﻿using DayuCode.Designer.Entity;
using DayuCode.Designer.Model;
using DayuCode.Designer.Service;
using DayuCode.Designer.Service.ui;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace DayuCode.Designer.Forms
{
    public partial class FormSourceCode : UIForm
    {
        Func func;
        string terminalType;
        private long projectId;
        private long funcId;
        private long pageLayoutId;
        IList<SourceCode> currSourceCodes;
        IList<SrcCodeConfig> srcCodeCfgs = null;
        public FormSourceCode(long projectId, long funcId, string terminalType)
        {
            InitializeComponent();
            txtSrcCode.IsReadOnly = true;

            cmbTerminalType.Items.Add(new CodeItem(TerminalType.WEB, "PC Web"));
            cmbTerminalType.Items.Add(new CodeItem(TerminalType.APP, "手机APP"));
            cmbTerminalType.Items.Add(new CodeItem(TerminalType.PAD, "平板PAD"));

            this.projectId = projectId;
            this.funcId = funcId;
            this.terminalType = terminalType;
            for (int i = 0; i < cmbTerminalType.Items.Count; i++)
            {
                if ((cmbTerminalType.Items[i] as CodeItem).Code.Equals(terminalType))
                {
                    cmbTerminalType.SelectedIndex = i;
                    break;
                }
            }

            func = FuncHandler.getFunc(funcId);

            getCodeTypes();

            loadDefaultBasePath();

            //GenSourceCode();
        }

        private void clearSourceCodes()
        {
            layoutSourceCodeFiles.Controls.Clear();
            txtSrcCode.Text = "";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="funcId"></param>
        /// <param name="codeType">1 java, 2 前端代码</param>
        private void GenSourceCode()
        {
            if (cmbCodeTypes.SelectedItem == null) return;
            string codeType = (cmbCodeTypes.SelectedItem as CodeItem).Code;
            srcCodeCfgs = AppInstance.SourceCodeConfig;
            layoutSourceCodeFiles.Controls.Clear();
            //生成代码
            layoutSourceCodeFiles.Controls.Clear();
            IList<SourceCode> srcCodes = SourceCodeHandler.generateCodes(funcId, terminalType, pageLayoutId, codeType);
            currSourceCodes = srcCodes;
            if (srcCodes != null)
            {
                foreach (SourceCode srccode in srcCodes)
                {
                    UILabel lbl = new UILabel();
                    lbl.Text = srccode.FilePath;
                    lbl.AutoSize = true;
                    lbl.Margin = new Padding(3, 2, 3, 2);
                    lbl.Padding = new Padding(0, 3, 0, 1);
                    lbl.BackColor = SystemColors.GradientActiveCaption;//  Color.FromArgb(80, 160, 255);
                    //lbl.ForeColor = Color.FromArgb(255, 255, 255);
                    lbl.Cursor = Cursors.Hand;
                    lbl.Tag = srccode;
                    lbl.Click += LblSourceFile_Click;
                    layoutSourceCodeFiles.Controls.Add(lbl);
                }
            }
        }

        private void getCodeTypes()
        {
            cmbCodeTypes.DataSource = null;
            if (cmbTerminalType.SelectedItem == null) return;
            if (func == null) return;
            string terminalType = (cmbTerminalType.SelectedItem as CodeItem).Code;
            long pagelayoutId = -1;
            if (TerminalType.APP.Equals(terminalType))
            {
                pagelayoutId = func.AppPageLayoutId??0;
            }else if (TerminalType.PAD.Equals(terminalType))
            {
                pagelayoutId = func.PadPageLayoutId ?? 0;
            }
            else
            {
                pagelayoutId = func.WebPageLayoutId ?? 0;
            }
            this.pageLayoutId = pagelayoutId;
            List<CodeItem> codeTypes = PageConfigHandler.getCodeTypes(pagelayoutId);
            cmbCodeTypes.DataSource = codeTypes;
            if(codeTypes.Count > 0)
            {
                cmbCodeTypes.SelectedIndex = 0;
            }
        }

        private void loadDefaultBasePath()
        {
            if (cmbTerminalType.SelectedItem == null) return;
            if (cmbCodeTypes.SelectedItem == null) return;
            string terminalType = (cmbTerminalType.SelectedItem as CodeItem).Code;
            string codeType = (cmbCodeTypes.SelectedItem as CodeItem).Code;
            //本地代码路径

            string basePath = SrcCodeConfig.GetBasePath(projectId, terminalType, codeType);
            txtBasePath.Text = basePath;
        }

        private void LblSourceFile_Click(object sender, EventArgs e)
        {
            txtSrcCode.ResetText();
            txtSrcCode.Invalidate();
            txtSrcCode.Refresh();

            UILabel lbl = sender as UILabel;
            SourceCode srccode = lbl.Tag as SourceCode;
            if (srccode != null)
            {
                txtSrcCode.Text = srccode.SrcCode;
            }
            foreach (Control control in layoutSourceCodeFiles.Controls)
            {
                control.BackColor = SystemColors.GradientActiveCaption;
            }
            lbl.BackColor = SystemColors.HighlightText;
        }

        private void btnChooseBasePath_Click(object sender, EventArgs e)
        {
            string basePath = txtBasePath.Text.Trim();
            if (Directory.Exists(basePath))
            {
                folderBrowserDialog1.SelectedPath = basePath;
            }
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtBasePath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnWriteSourceCodeFile_Click(object sender, EventArgs e)
        {
            if (currSourceCodes == null || currSourceCodes.Count == 0)
            {
                this.ShowErrorTip("请【生成代码】后再保存到本地文件！");
                return;
            }
            if (cmbTerminalType.SelectedItem == null) return;
            string terminalType = (cmbTerminalType.SelectedItem as CodeItem).Code;

            if (cmbCodeTypes.SelectedItem == null) return;
            string codeType = (cmbCodeTypes.SelectedItem as CodeItem).Code;

            string basePath = txtBasePath.Text.Trim();
            
            SrcCodeConfig.SetBasePath(projectId, terminalType, codeType, basePath);
            SrcCodeConfig.SaveConfig(AppInstance.SourceCodeConfig);

            if (string.IsNullOrEmpty(basePath))
            {
                MessageBox.Show(this, "还未填写代码的本地保存目录");
                return;
            }
            if (!Directory.Exists(basePath))
            {
                MessageBox.Show(this, "保存目录不存在：" + basePath);
                return;
            }
            if (basePath.ToLower().Contains("dayu-framework"))
            {
                MessageBox.Show(this, "保存目录不能包含'dayu-framework'目录,请选择其他目录" + basePath);
                return;
            }

            DateTime dtime = DateTime.Now;
            string backupDir = Path.Combine(AppInstance.StartupPath, "backup\\" + dtime.ToString("yyyy-MM-dd") + "\\" + dtime.ToString("HHmmss") + "\\");
            Directory.CreateDirectory(backupDir);

            foreach (SourceCode srccode in currSourceCodes)
            {
                string filePath = Path.Combine(basePath, srccode.FilePath);
                FileInfo fileInfo = new FileInfo(filePath);
                if (!fileInfo.Directory.Exists)
                {
                    fileInfo.Directory.Create();
                }
                if (File.Exists(filePath))
                {
                    string backFile = Path.Combine(backupDir, srccode.FilePath);
                    FileInfo backfileInfo = new FileInfo(backFile);
                    Directory.CreateDirectory(backfileInfo.Directory.FullName);
                    File.Copy(filePath, backFile);
                }
                File.WriteAllText(filePath, srccode.SrcCode);
            }
            (this.FindForm() as UIForm).ShowSuccessTip("保存完成");
        }

        private void cmbTerminalType_SelectedIndexChanged(object sender, EventArgs e)
        {
            getCodeTypes();
        }

        private void cmbCodeTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadDefaultBasePath();
            if (currSourceCodes != null)
            {
                currSourceCodes.Clear();
            }
            layoutSourceCodeFiles.Controls.Clear();
        }

        private void btnGenCode_Click(object sender, EventArgs e)
        {
            GenSourceCode();
        }

        private void lblBackupDir_Click(object sender, EventArgs e)
        {
            string backupDir = Path.Combine(AppInstance.StartupPath, "backup");
            System.Diagnostics.Process.Start("explorer.exe", backupDir);
        }
    }
}